package com.lnj.community.config;

import com.lnj.community.filter.JwtAuthenticationFilter;
import com.lnj.community.utiles.CommunityConstant;
import com.lnj.community.utiles.CommunityUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;

@Configuration
@EnableWebSecurity // 启用 Spring Security 的 Web 安全支持
public class SecurityConfig implements CommunityConstant {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http
                // 配置安全匹配路径，匹配所有请求
                .securityMatcher("/**")
                .authorizeHttpRequests(auth -> auth
                        // 这里是需要登录才能访问的路径
                        .requestMatchers("/user/setting", "/user/upload", "/discuss/add", "/comment/add/**", "/letter/**",
                                "/notice/**", "/like","/follow", "/unfollow")
                        .hasAnyAuthority(AUTHORITY_USER,AUTHORITY_MODERATOR,AUTHORITY_ADMIN)
                        // 匹配 /discuss/top 和 /discuss/wonderful 路径，需要版主权限
                        .requestMatchers("/discuss/top", "/discuss/wonderful").hasAnyAuthority(AUTHORITY_MODERATOR,AUTHORITY_ADMIN)
                        // 匹配 /discuss/delete 和 /data/** 路径，需要管理员权限
                        .requestMatchers("/discuss/delete", "/data/**","/actuator/**").hasAnyAuthority(AUTHORITY_ADMIN)
                        // 其他路径权限配置，可按需添加
                        .anyRequest().permitAll()
                )
                .formLogin(form -> form
                       .loginPage("/login")
                       .loginProcessingUrl("/community/login")
                       .successHandler((request, response, authentication) -> {
                           // 登录成功后，重定向到首页
                           response.sendRedirect("/community/index");
                       })
                       .failureHandler((request, response, exception) -> {
                           // 失败后，重定向到登录页
                           request.getSession().setAttribute("error", "账号或密码错误");
                           response.sendRedirect("/community/login");
                       })
                )
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)

                .exceptionHandling(exception -> exception
                        // 没有登录
                        .authenticationEntryPoint((request, response, authException) -> {
                            String xRequestedWith = request.getHeader("x-requested-with");
                            if ("XMLHttpRequest".equals(xRequestedWith)) {
                                try {
                                    response.setContentType("application/plain;charset=utf-8");
                                    response.getWriter().write(CommunityUtil.getJSONString(403, "你还没有登录哦!"));
                                } catch (IOException e) {
                                    // 处理异常，可根据实际情况记录日志
                                    e.printStackTrace();
                                }
                            } else {
                                response.sendRedirect(request.getContextPath() + "/login");
                            }
                        })
                        // 权限不足
                        .accessDeniedHandler((request, response, accessDeniedException) -> {
                            String xRequestedWith = request.getHeader("x-requested-with");
                            if ("XMLHttpRequest".equals(xRequestedWith)) {
                                try {
                                    response.setContentType("application/plain;charset=utf-8");
                                    response.getWriter().write(CommunityUtil.getJSONString(403, "你没有访问此功能的权限!"));
                                } catch (IOException e) {
                                    // 处理异常，可根据实际情况记录日志
                                    e.printStackTrace();
                                }
                            } else {
                                response.sendRedirect(request.getContextPath() + "/denied");
                            }
                        }))
                // 关闭 CSRF 保护（开发环境可关闭，生产环境建议开启）
                .csrf(csrf -> csrf.disable())
                .logout(logout -> logout
                        .logoutUrl("/securitylogout")
                        .logoutSuccessUrl("/index"));

        return http.build();
    }
}